package fr.emse.tatiana.filter;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import com.qizx.api.ModuleResolver;
import com.qizx.util.basic.Check;

public class TatianaModuleResolver implements ModuleResolver {

	private URL base;

	/**
	 * Creates a resolver using a base URL. 
	 * @param base an URL used as a base for resolving module URI's. 
	 */
	public TatianaModuleResolver(URL base)
	{
		Check.nonNull(base, "base URL");
		this.base = base;
		// due to weird behavior of URL class, need a trailing slash:
		if(base != null && !base.getPath().endsWith("/")) {
			try {
				this.base = new URL(base.getProtocol(), base.getHost(),
						base.getPath() + "/");
			}
			catch (MalformedURLException e) { // what to do ?
				e.printStackTrace();
			}
		}
	}

	// if there are hints, go with hints first.

	public URL[] resolve(String moduleNamespaceURI, String[] locationHints)
	throws MalformedURLException 
	{
		URL attempt = new URL(base, moduleNamespaceURI);


		// try hints:
		if(locationHints == null || locationHints.length == 0) {
			if(!nonExistentFile(attempt))
				return new URL[] { attempt }; 
			else 
				return new URL[0]; // failure
		} else {

			int hintCnt = locationHints.length;
			ArrayList<URL> result = new ArrayList<URL>(hintCnt);
			for (int i = 0; i < locationHints.length; i++) {
				URL url = new URL(base, locationHints[i]);

				if(!nonExistentFile(url))
					result.add(url);
			}
			return result.toArray(new URL[result.size()]);
		}
	}

	// returns true if file: and (does not exist or not plain)
	private boolean nonExistentFile(URL url)
	{
		if(!"file".equals(url.getProtocol()))
			return false;
		File file = new File(url.getPath());
		return ! file.isFile();
	}

}
